# -*- coding: utf-8 -*-
"""
浏览器信息获取（基于系统等级）
@author:   XueJunJie
@file:     BrowInfoFetch.py
@date:     2024-9-23
@version:  1.1.0
"""
import os
import re
import winreg
import getpass
import warnings
import platform
from typing import Union

from . import _chrome_guess_paths, _chrome_guess_auto_down_paths

__all__ = [
    "get_chrome_path",
    "get_chrome_version",
    "guess_chrome_auto_down_path",
    "fetch_user_data_dir",
]


def guess_chrome_path() -> str:
    """猜测chrome路径(旧方法在未来可能弃用)"""
    warnings.warn("guess_chrome_path may be abandoned in the future, please use get_chrome_path")
    for _p in _chrome_guess_paths:
        if os.path.isfile(_p):
            return _p
    return ""


def get_chrome_path() -> Union[str, None]:
    """猜测chrome路径(新版)"""
    try:
        key_path = r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path)
        # 获取Chrome的安装路径
        chrome_path, _ = winreg.QueryValueEx(key, "")
        winreg.CloseKey(key)
        return chrome_path
    except Exception as e:
        return None


def get_chrome_version__old(chrome_dir="") -> str:
    """获取chrome的版本。不传路径则尝试自动识别"""
    warnings.warn("get_chrome_version__old may be abandoned in the future, please use get_chrome_version")
    if not chrome_dir:
        path = guess_chrome_path()
        chrome_dir, _ = os.path.split(path)
    assert os.path.isdir(chrome_dir), "Unknow chrome dir path"
    chrome_ver = ""
    newest = 0
    for _, dirs, files in os.walk(chrome_dir):
        # 如果是更新交接点，会存在新旧双版本。启动默认最新，所以必须筛选出最新版
        # 默认启动为旧版，直到更新完成
        for dir in dirs:
            res = re.findall("^((\d+)\.\d+\.\d+\.\d+)", dir)
            if res:
                _chrome_ver, _id = res[0]
                if int(_id) > newest:
                    newest = int(_id)
                    chrome_ver = _chrome_ver
                    # 默认其实启动是旧版，不选择最新版
                    break
        break
    if not chrome_ver:
        raise Exception("unknow chrome version")
    return chrome_ver


def get_chrome_version(chrome_dir: str = "") -> str:
    """
    获取chrome版本号(新版)
    :param chrome_dir: str : chrome安装目录,不填则在注册表中获取。携带版浏览器必须指定
    :return: str : chrome版本号
    """
    if not chrome_dir:
        try:
            # 打开注册表项以查找Chrome的版本
            key_path_version = r"SOFTWARE\Google\Chrome\BLBeacon"
            key_version = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path_version)
            # 获取Chrome的版本
            chrome_version, _ = winreg.QueryValueEx(key_version, "version")
            winreg.CloseKey(key_version)
            return chrome_version
        except Exception as e:
            return ""
    else:
        assert os.path.isdir(chrome_dir), "Unknow chrome dir path"
        chrome_ver = ""
        newest = 0
        for _, dirs, _ in os.walk(chrome_dir):
            # 如果是更新交接点，会存在新旧双版本。启动默认最新，所以必须筛选出最新版
            # 默认启动为旧版，直到更新完成
            for dir in dirs:
                res = re.findall("^((\d+)\.\d+\.\d+\.\d+)", dir)
                if res:
                    _chrome_ver, _id = res[0]
                    if int(_id) > newest:
                        newest = int(_id)
                        chrome_ver = _chrome_ver
                        # 默认其实启动是旧版，不选择最新版
                        break
            break
        return chrome_ver


def guess_chrome_auto_down_path() -> str:
    """猜测chrome自动下载路径"""
    for _p in _chrome_guess_auto_down_paths:
        if os.path.isdir(_p):
            return _p
    return ""


def fetch_user_data_dir() -> str:
    """
    获取chrome用户数据目录
    """
    if "window" in platform.system().lower():
        _old_path = rf"C:\Users\{getpass.getuser()}\AppData\Local\Google\Chrome\User Data"
    else:
        _old_path = ""
    return _old_path


def get_chrome_version_by_error(message=""):
    """
    通过错误信息捕获chrome版本
    :message    str    异常信息文本
    res:
        str     提取到的chrome版本号文本
    """
    try:
        return re.findall("browser version is ([\d\.]+)", message)[0]
    except Exception as e:
        return ""


def get_driver_version(chromedriver_path: str = r"chromedriver.exe"):
    """获取driver版本,默认driver在当前路径"""
    if "window" in platform.system().lower():
        order = rf"{chromedriver_path} --version".replace("/", "\\")
    else:
        order = rf"{chromedriver_path} --version".replace("\\", "/")
    info = os.popen(order).read()
    res = re.findall("\d+\.\d+\.\d+\.\d+", info)
    if not res:
        raise Exception("unknow driver version")
    return res[0]
